package com.gold.config.client;

import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class ConfigClientAutoConfiguration {

    @Bean
    public ConfigClientProperties configClientProperties(Environment environment, ApplicationContext context)
    {
        if ((context.getParent() != null) &&
                (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context
                        .getParent(), ConfigClientProperties.class).length > 0)) {
            return (ConfigClientProperties)BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(), ConfigClientProperties.class);
        }
        ConfigClientProperties client = new ConfigClientProperties(environment);
        return client;
    }

    @Bean
    public ConfigClientHealthProperties configClientHealthProperties()
    {
        return new ConfigClientHealthProperties();
    }

    @Configuration
    @ConditionalOnClass({HealthIndicator.class})
    @ConditionalOnBean({ConfigServicePropertySourceLocator.class})
    @ConditionalOnProperty(value={"health.config.enabled"}, matchIfMissing=true)
    protected static class ConfigServerHealthIndicatorConfiguration
    {
        @Bean
        public ConfigServerHealthIndicator configServerHealthIndicator(ConfigServicePropertySourceLocator locator, ConfigClientHealthProperties properties, Environment environment)
        {
            return new ConfigServerHealthIndicator(locator, environment, properties);
        }
    }

    @Configuration
    @ConditionalOnClass({ContextRefresher.class})
    @ConditionalOnBean({ContextRefresher.class})
    @ConditionalOnProperty({"spring.cloud.config.watch.enabled"})
    protected static class ConfigClientWatchConfiguration
    {
        @Bean
        public ConfigClientWatch configClientWatch(ContextRefresher contextRefresher)
        {
            return new ConfigClientWatch(contextRefresher);
        }
    }

}
